package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/10/27 10:35
 */
@RestController
@RequestMapping("friend")
@CrossOrigin
public class FriendController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FriendService friendService;
    @Autowired
    private NoFriendService noFriendService;
    @Autowired
    private UserClient userClient;
    //1.添加好友
    @PutMapping("like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type){
        //1.1)从请深圳市作用域中得到claims
        Claims claims = (Claims) request.getAttribute("claims");
        //1.2)判断是否有值
        if(claims == null){
            return new Result(StatusCode.ACCESSERROR,false,"无访问权限！");
        }
        //1.3)根据类型，添加好友
        if(type.equals("1")){       //type=1:  代表喜欢，此时操作的是好友表
            //1.3.1)在好友表中添加记录
            int count = friendService.addFriend(claims.getId(),friendid);

            //1.3.2)修改用户表的关注数及粉丝数(需要用到 openFeign)
            userClient.incFansCount(friendid,1);            //修改粉丝数
            userClient.incFollowCount(claims.getId(),1);    //修改关注数

            //1.3.3)如果说用户表中有此记录，就提示：重复添加
            if(count == 0){
                return new Result(StatusCode.REPERROR,false,"重复添加好友错误！");
            }
        }else{
            // return new Result(StatusCode.OK,true,"添加非好友成功！");
            noFriendService.addNoFriend(claims.getId(),friendid);
        }
        return new Result(StatusCode.OK,true,"添加好友成功！");
    }
    //2.删除好友
    @DeleteMapping("{friendid}")
    public Result delete(@PathVariable String friendid){
        //1.1)从请深圳市作用域中得到claims
        Claims claims = (Claims) request.getAttribute("claims");
        //1.2)判断是否有值
        if(claims == null){
            return new Result(StatusCode.ACCESSERROR,false,"无访问权限！");
        }
        //1.3)在好友表中删除记录并添加记录到非好友表中
        friendService.deleteFriend(claims.getId(),friendid);
        //1.4）修改粉丝数及关注数
        userClient.incFansCount(friendid,-1);
        userClient.incFollowCount(claims.getId(),-1);

        return new Result(StatusCode.OK,true,"删除好友成功！");
    }
}
